package com.luoran.system.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.luoran.common.core.utils.PrimaryKeyIdUtils;
import com.luoran.system.domain.dto.EchartsEntity;
import com.luoran.system.domain.dto.RoleDataListener;
import com.luoran.system.utils.RowSameValueMergeStrategy;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.luoran.common.core.constant.UserConstants;
import com.luoran.common.core.utils.SecurityUtils;
import com.luoran.common.core.utils.poi.ExcelUtil;
import com.luoran.common.core.web.controller.BaseController;
import com.luoran.common.core.web.domain.AjaxResult;
import com.luoran.common.core.web.page.TableDataInfo;
import com.luoran.common.log.annotation.Log;
import com.luoran.common.log.enums.BusinessType;
import com.luoran.common.security.annotation.PreAuthorize;
import com.luoran.system.api.domain.SysRole;
import com.luoran.system.service.ISysRoleService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 角色信息
 *
 * @author guohailong
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.url}")
    private String url;


    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/list")
    public TableDataInfo list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) throws IOException {
        List<SysRole> list = roleService.selectRoleList(role);
        //要合并的列
        int[] mergeColumnIndexArray = {2};

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("角色", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        int pageSize = 1030000;
        int totalCount = list.size();
        int numPages = (totalCount + pageSize -1)/pageSize;
        // 创建 ExcelWriter 对象，写入到输出流中
        ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), SysRole.class);
        ExcelWriter writer = writerBuilder.build(); // 在这里创建 ExcelWriter
        try {
            for (int i = 0; i < numPages; i++) {
                int startIndex = i * pageSize;
                int endIndex = Math.min(startIndex + pageSize, totalCount);
                // 获取当前页的数据
                List<SysRole> pageData = list.subList(startIndex, endIndex);
                // 创建 WriteSheet 对象，指定页码和工作表名称
                WriteSheet writeSheet = EasyExcel.writerSheet("Sheet " + (i + 1)).build();
                // 注册合并策略并写入当前页数据到指定工作表
                writerBuilder.registerWriteHandler(new RowSameValueMergeStrategy(mergeColumnIndexArray));
                writer.write(pageData, writeSheet); // 使用 writer.write() 方法
            }
        } finally {
            writer.finish(); // 关闭 writer，确保文件生成
        }
    }


    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:role:export")
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file) throws IOException {

        try {
            EasyExcel.read(file.getInputStream(), SysRole.class, new RoleDataListener(roleService)).doReadAll();
//            ArrayList<Callable<Object>> tasks = new ArrayList<>();
//
//            for (int i = 0; i < 3; i++) {
//                int num = i;
//                tasks.add(()->{
//                    EasyExcel.read(file.getInputStream(), SysRole.class,new RoleDataListener(roleService))
//                            .sheet(num).doRead();
//                    return null;
//                });
//            }
            // 使用 ExecutorService 执行任务
//            ExecutorService executorService = Executors.newFixedThreadPool(tasks.size());
//            try {
//                executorService.invokeAll(tasks);
//            } catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//                throw new RuntimeException(e);
//            } finally {
//                executorService.shutdown();
//            }


            return AjaxResult.success();
        } catch (Exception aa) {
            aa.printStackTrace();
            return AjaxResult.error();
        }
    }


    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }



        @PostMapping("uploadRoleHeader")
    public AjaxResult uploadRoleHeader(MultipartFile file) {

        String fileName = "/"+UUID.randomUUID()+"_"+file.getOriginalFilename();

        try {

            minioClient.putObject(PutObjectArgs.builder()
                    .object(fileName)
                    .bucket(bucketName)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build());
            return AjaxResult.success(url+ "/" +bucketName+ fileName);

        } catch (Exception aa) {
            aa.printStackTrace();
            return AjaxResult.error();
        }

    }


    @GetMapping("chartsOne")
    public AjaxResult chartsOne() {
        List<EchartsEntity> list = roleService.getChartsOne();
        return AjaxResult.success(list);
    }

    @GetMapping("chartsTwo")
    public AjaxResult chartsTwo() {
        List<EchartsEntity> list = roleService.chartsTwo();
        return AjaxResult.success(list);
    }

    @GetMapping("chartsThree")
    public AjaxResult chartsThree() {
        List<EchartsEntity> list = roleService.chartsThree();
        return AjaxResult.success(list);
    }

    /**
     * 新增角色
     */
    @PreAuthorize(hasPermi = "system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setRoleId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize(hasPermi = "system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds) {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return AjaxResult.success(roleService.selectRoleAll());
    }
}
